﻿$(function () {
    var jstreeObj = $('#jstree');
    jstreeObj.jstree({
        "plugins": ["wholerow", "dnd"],
        "core": {
            "check_callback": true
        }
    });

    $('#sortForm')
        .submit(function () {
            try {
                window.sort = 1;
                var jsonData = $('#jstree').jstree(true).get_json('#', { flat: false });
                var arr = [];
                for (x in jsonData) {
                    var menuid = jsonData[x]["li_attr"]["data-menuid"];
                    var obj = { id: menuid, parentid: 0, sort: sort++ };
                    arr.push(obj);
                    getChild(jsonData[x].children, obj, arr);
                }
                var jsonStr = JSON.stringify(arr);
                console.log(arr);
                $('#result').val(jsonStr);

                ajaxSubmit(jsonStr);

                return false;
            }
            catch (e) {
                console.log(e);
                return false;
            }
        });

    function ajaxSubmit(str) {
        $.post(postUrl, {result:str},
            function (ajaxMsg) {
                msgBox.showMsg(ajaxMsg);
                comm.ajaxSuccess(ajaxMsg);
            },
            'json');
    }

    function getChild(childs, obj, arr) {
        if (!!childs) {
            for (item in childs) {
                var menuid = childs[item]["li_attr"]["data-menuid"];
                var obj2 = { id: menuid, parentid: obj.id, sort: sort++ };
                arr.push(obj2);
                getChild(childs[item].children, obj2, arr);
            }
        }
    }
})